public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val = val;
        }
    }
    public TreeNode root;
    public TreeNode search(int val){
        TreeNode cur = root;
        if (root == null){
            return null;
        }
        while (cur != null){
            if ((val < cur.val)){
                cur = cur.left;
            }else if (val > cur.val){
                cur = cur.right;
            }else {
                return cur;
            }
        }
        return null;
    }
    //二叉搜索树在插入数据的时候一定是插入到叶子位置
    //不能插入两个值相同的节点
    public boolean insert(int val){
        TreeNode node = new TreeNode(val);
        if (root == null){
            root = node;
            return true;
        }
        TreeNode cur = root;
        TreeNode parent = root;
        while (cur != null){
            if (cur.val < val){
                parent = cur;
                cur = cur.right;
            }else if (cur.val == val){
                return false;//不能插入相同的节点
            }else {
                parent = cur;
                cur = cur.left;
            }
        }
        if (parent.val < val){
            parent.right = node;
        }
        if (parent.val > val){
            parent.left = node;
        }
        return true;
    }
    public void removeNode(int key){
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if (cur.val < key){
                parent = cur;
                cur = cur.right;
            }else if (cur.val > key){
                parent = cur;
                cur = cur.left;
            }else {
                remove(cur, parent);
                return ;
            }
        }
    }

    private void remove(TreeNode cur, TreeNode parent) {
        if (cur.left == null){
            if (cur == root){
                root = cur.right;
            }else if (cur == parent.left){
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if (cur.right == null){
            if (cur == root){
                root = cur.left;
            }else if (cur == parent.left){
                parent.left = cur.left;
            }else {
                parent.right = cur.left;
            }
        }else {
            //此时cur的左右节点都不为空,使用二叉树搜索树删除的方式为替罪羊删除法：将删除节点其右树的最小值放在删除节点处
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target.left != null){
                targetParent = target;
                target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }

        }
    }

}
